package com.mediacloud.app.newsmodule.fragment.activity;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mediacloud.app.assembly.interfaces.LoadNetworkBack;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.BaseMessageReciver;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.activity.ActivityListAdaptor;
import com.mediacloud.app.newsmodule.adaptor.bigimg_nosliceline.BigImageNoSliceLineAdaptor;
import com.mediacloud.app.newsmodule.adaptor.dialog.CheckableLayout;
import com.mediacloud.app.newsmodule.adaptor.dialog.ScreeningAdapter;
import com.mediacloud.app.newsmodule.adaptor.dialog.TagSelectBean;
import com.mediacloud.app.newsmodule.fragment.BaseNewsListFragment;
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils;
import com.mediacloud.app.reslib.enums.StyleOther;
import com.mediacloud.app.reslib.util.DataInvokeUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 活动列表
 */
public class ActivityListFragment extends BaseNewsListFragment implements View.OnClickListener {

    private Dialog dialog;
    private EditText etNavSearch;
    private ImageView ivSearchCancel;
    private TextView tvSearchCancel;
    private TextView tvNavType;
    private TextView tvNavState;
    private LinearLayout llNavType;
    private LinearLayout llNavState;
    private ImageView ivTriangleType;
    private ImageView ivTriangleState;

    private final List<TagSelectBean> mListData = new ArrayList<>();
    private final List<TagSelectBean> ListStateData = new ArrayList<>();
    private List<TagSelectBean> ListTypeData = new ArrayList<>();
    private ScreeningAdapter screeningAdapter;

   ：public static final Set<Integer> positionSet=new HashSet<>();
    private static final Set<Integer> positionSetType = new HashSet<>();
    private static final Set<Integer> positionSetState = new HashSet<>();
    private final boolean selectMode = false; //选择模式 多选或者单选  true-->多选
    private String selectTypeName = "";
    private String selectStateName = "";
    private String selectTypeId = "";
    private String selectStateId = "";
    public static  final int type = 1;//1代表类型，2代表状态
    // 图片是否已倒立
    private boolean typeFlag = false;
    private boolean stateFlag = false;
    private PopupWindow mPopWindow;

    private Map<String, String> contentParams = new HashMap<>();

    public ActivityListFragment() {

    }

    @Override
    public int getLayoutResID() {
        return R.layout.aappfactory_fragment_activitylist;
    }

    @Override
    protected void getNewsListData() {
        matchLBSCataglogId();
        if (dataInvoker != null && catalogID != null) {
            contentParams.put("model_id", selectTypeId);
            contentParams.put("type", selectStateId);
            contentParams.put("keyword", etNavSearch.getText().toString() + "");
            dataInvoker.getContentListWithAd(catalogID, pageNum, pageSize, contentParams);
        }
    }

    @Override
    public void onLoadMore() {
        if (isLoading)
            return;
        pageNum++;
        isLoading = true;
        loadmore();
    }


    private void getActivityTypeData() {
        DataInvokeUtil.activeTypeList(new LoadNetworkBack<BaseMessageReciver>() {
            @Override
            public void Success(BaseMessageReciver result) {
                if (result.state) {
                    try {
                        JSONObject data = result.orginData.optJSONObject("data");
                        if (data != null) {
                            JSONArray meta = data.optJSONArray("meta");
                            if (meta != null) {
                                ListTypeData = FunKt.jsonToArrayList(meta.toString(), TagSelectBean.class);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void Failure(Object obj) {
            }

            @Override
            public void otherData(String result) {
            }
        }, new BaseMessageReciver());
    }

    @Override
    public void initView() {
        super.initView();

        etNavSearch = findViewById(R.id.et_active_search);
        ivSearchCancel = findViewById(R.id.iv_active_search_cancel);
        tvSearchCancel = findViewById(R.id.tv_active_search_cancel);
        tvNavType = findViewById(R.id.tv_nav_type);
        tvNavState = findViewById(R.id.tv_nav_state);
        llNavType = findViewById(R.id.ll_nav_type);
        llNavState = findViewById(R.id.ll_nav_state);
        ivTriangleType = findViewById(R.id.iv_nav_triangle_type);
        ivTriangleState = findViewById(R.id.iv_nav_triangle_state);

        ivSearchCancel.setOnClickListener(this);
        tvSearchCancel.setOnClickListener(this);
        llNavType.setOnClickListener(this);
        llNavState.setOnClickListener(this);

        getActivityTypeData();
        //软件盘搜索按钮监听
        etNavSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    hideKeyBroad();
                    f5();
                }
                return false;
            }
        });
        etNavSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    ivSearchCancel.setVisibility(View.GONE);
                    tvSearchCancel.setVisibility(View.GONE);
                } else {
                    ivSearchCancel.setVisibility(View.VISIBLE);
                    tvSearchCancel.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //如果有其他样式的 就用这个列表样式了
        if (catalogItem != null && catalogItem.getCatalogStyle() == StyleOther.OtherStyle)//&&catalogItem.getStyleOther()!=null)
        {
            adaptor = new BigImageNoSliceLineAdaptor(getActivity(), catalogItem, playClickListener);
        } else
            adaptor = new ActivityListAdaptor(getActivity(), catalogItem);

        mCatalogContentItemListView.setAdapter(adaptor);
    }

/*    private void showDialog(View customView) {
        //<style name="dialogNavSelect" parent="@android:style/Theme.Panel"/> 可选择这个style
        dialog = new Dialog(getActivity(), R.style.shanShiPinDialogStyle);
        View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_nav_screen_layout, null);

        mRecyclerView = inflate.findViewById(R.id.rv_dialog_nav_select);
        TextView tvReset = inflate.findViewById(R.id.tv_dialog_nav_reset);
        TextView tvYes = inflate.findViewById(R.id.tv_dialog_nav_yes);
        View llOutside = inflate.findViewById(R.id.ll_dialog_outside);

        //弹窗点击周围空白处弹出层自动消失弹窗消失(false时为点击周围空白处弹出层不自动消失)
        dialog.setCanceledOnTouchOutside(false);
        //将布局设置给Dialog
        dialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window window = dialog.getWindow();

        WindowManager.LayoutParams wlp = window.getAttributes();

        //获取通知栏高度  重要的在这，获取到通知栏高度
        int notificationBar = Resources.getSystem().getDimensionPixelSize(Resources.getSystem().getIdentifier("status_bar_height", "dimen", "android"));
        //获取控件 textview 的绝对坐标,( y 轴坐标是控件上部到屏幕最顶部（不包括控件本身）)
        //location [0] 为x绝对坐标;location [1] 为y绝对坐标
        int[] location = new int[2];

        customView.getLocationInWindow(location); //获取在当前窗体内的绝对坐标
        customView.getLocationOnScreen(location);//获取在整个屏幕内的绝对坐标

        wlp.x = 0; //对 dialog 设置 x 轴坐标
        wlp.y = location[1] + customView.getHeight() - notificationBar; //对dialog设置y轴坐标
        wlp.gravity = Gravity.TOP;
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        window.setAttributes(wlp);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        initData();
        initListener();
        llOutside.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
            }
        });
        tvReset.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onClick(View v) {
                positionSet.clear();
                dialog.cancel();
            }
        });
        tvYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(selectName)) {
                    if (type == 1) {
                        tvNavType.setTextColor(getResources().getColor(R.color.color_e41d1d));
                        ivTriangleType.setImageDrawable(getResources().getDrawable(R.drawable.icon_triangle_down_red));
                        tvNavType.setText(selectName);
                    } else if (type == 2) {
                        tvNavState.setTextColor(getResources().getColor(R.color.color_e41d1d));
                        ivTriangleState.setImageDrawable(getResources().getDrawable(R.drawable.icon_triangle_down_red));
                        tvNavState.setText(selectName);
                    }
                } else {
                    if (type == 1) {
                        tvNavType.setTextColor(getResources().getColor(R.color.color_222));
                        ivTriangleType.setImageDrawable(getResources().getDrawable(R.drawable.icon_triangle_down));
                    } else if (type == 2) {
                        tvNavState.setTextColor(getResources().getColor(R.color.color_222));
                        ivTriangleState.setImageDrawable(getResources().getDrawable(R.drawable.icon_triangle_down));
                    }
                }
                dialog.cancel();
            }
        });
        //dialog取消监听
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (type == 1) {
                    imgRateType(ivTriangleType);
                } else if (type == 2) {
                    imgRateState(ivTriangleState);
                }
            }
        });
        dialog.show();//显示对话框

    }*/

    private void showPopWindow() {
        View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_nav_screen_layout, null);

        RecyclerView mRecyclerView = inflate.findViewById(R.id.rv_dialog_nav_select);
        TextView tvReset = inflate.findViewById(R.id.tv_dialog_nav_reset);
        TextView tvYes = inflate.findViewById(R.id.tv_dialog_nav_yes);
        View llOutside = inflate.findViewById(R.id.ll_dialog_outside);

        mPopWindow = new PopupWindow(inflate);
        mPopWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mPopWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopWindow.setFocusable(true);//设置再次点击控件的时候，关闭窗口，不重新打开
        mPopWindow.setOutsideTouchable(false);
        mPopWindow.setTouchable(true);
        // 显示在某个控件的正左下方，无偏移
        mPopWindow.showAsDropDown(llNavType);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        initData();
        screeningAdapter = new ScreeningAdapter(mListData, positionSet);
        mRecyclerView.setAdapter(screeningAdapter);
        initListener();
        llOutside.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();
            }
        });
        tvReset.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onClick(View v) {
                positionSet.clear();
                if (type == 1) {
                    tvNavType.setTextColor(getResources().getColor(R.color.color_222));
                    ivTriangleType.setImageDrawable(getResources().getDrawable(R.drawable.icon_triangle_down));
                    tvNavType.setText("活动类型");
                    selectTypeId = "";
                    selectTypeName = "";
                } else if (type == 2) {
                    tvNavState.setTextColor(getResources().getColor(R.color.color_222));
                    ivTriangleState.setImageDrawable(getResources().getDrawable(R.drawable.icon_triangle_down));
                    tvNavState.setText("活动状态");
                    selectStateId = "";
                    selectStateName = "";
                }
                f5();
                mPopWindow.dismiss();
            }
        });
        tvYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (positionSet.size() > 0) {
                    if (type == 1) {
                        tvNavType.setTextColor(getResources().getColor(R.color.color_e41d1d));
                        ivTriangleType.setImageDrawable(getResources().getDrawable(R.drawable.icon_triangle_down_red));
                        tvNavType.setText(selectTypeName);
                    } else if (type == 2) {
                        tvNavState.setTextColor(getResources().getColor(R.color.color_e41d1d));
                        ivTriangleState.setImageDrawable(getResources().getDrawable(R.drawable.icon_triangle_down_red));
                        tvNavState.setText(selectStateName);
                    }
                } else {
                    if (type == 1) {
                        tvNavType.setTextColor(getResources().getColor(R.color.color_222));
                        ivTriangleType.setImageDrawable(getResources().getDrawable(R.drawable.icon_triangle_down));
                        tvNavType.setText("活动类型");
                        selectTypeId = "";
                        selectTypeName = "";
                    } else if (type == 2) {
                        tvNavState.setTextColor(getResources().getColor(R.color.color_222));
                        ivTriangleState.setImageDrawable(getResources().getDrawable(R.drawable.icon_triangle_down));
                        tvNavState.setText("活动状态");
                        selectStateId = "";
                        selectStateName = "";
                    }
                }
                f5();
                mPopWindow.dismiss();
            }
        });
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (type == 1) {
                    imgRateType(ivTriangleType);
                } else if (type == 2) {
                    imgRateState(ivTriangleState);
                }
            }
        });
    }

    private void initData() {
        if (type == 1) {
            mListData.clear();
            if (ListTypeData != null) {
                mListData.addAll(ListTypeData);
            }
        } else {
            mListData.clear();
            ListStateData.clear();
            ListStateData.add(new TagSelectBean("0", "筹备中"));
            ListStateData.add(new TagSelectBean("1", "进行中"));
            ListStateData.add(new TagSelectBean("2", "已结束"));
            ListStateData.add(new TagSelectBean("3", "已下线"));
            mListData.addAll(ListStateData);
        }
    }

    private void initListener() {
        screeningAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CheckableLayout rootLayout = view.findViewById(R.id.root_layout);
                rootLayout.setChecked(true);
                if (!selectMode) {
                    if (!positionSet.contains(position)) {
                        // 选择不同的单位时取消之前选中的单位
                        positionSet.clear();
                    }
                }
                addOrRemove(position);
                if (type == 1) {
                    selectTypeName = mListData.get(position).getName();
                    selectTypeId = mListData.get(position).getId();
                } else {
                    selectStateName = mListData.get(position).getName();
                    selectStateId = mListData.get(position).getId();
                }
            }
        });
    }

    @SuppressLint("NotifyDataSetChanged")
    private void addOrRemove(int position) {
        if (positionSet.contains(position)) {
            positionSet.remove(position);
        } else {
            positionSet.add(position);
        }
        // 更新列表界面，否则无法显示已选的item
        screeningAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        int index = position;
        index = index - mCatalogContentItemListView.getHeaderViewsCount();
        if (index < 0)
            return;
        ArticleItem item = (ArticleItem) adaptor.getItem(index);
        if (item.getType() != TypeX.CUSTOM.ADVERT) {
            item.setParentId(catalogID);
            item.setLinkNews(false);
            item.setType(TypeX.CUSTOM.ACTIVITY);
        }
        NewsItemClickUtils.OpenItemNewsHandle(getActivity(), item.getType(), item, catalogItem);
    }

    private void imgRateType(ImageView imageView) {
        if (typeFlag) {
            // 顺时针旋转180度
            ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(imageView, "rotation", 180f, 0f);
            objectAnimator.setDuration(300).start();
            typeFlag = false;
        } else {
            // 逆时针旋转180度
            ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(imageView, "rotation", 0f, 180f);
            objectAnimator.setDuration(300).start();
            typeFlag = true;
        }
    }

    private void imgRateState(ImageView imageView) {
        if (stateFlag) {
            // 顺时针旋转180度
            ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(imageView, "rotation", 180f, 0f);
            objectAnimator.setDuration(300).start();
            stateFlag = false;
        } else {
            // 逆时针旋转180度
            ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(imageView, "rotation", 0f, 180f);
            objectAnimator.setDuration(300).start();
            stateFlag = true;
        }
    }

    protected void hideKeyBroad() {
        final View v = getActivity().getWindow().peekDecorView();
        if (v != null && v.getWindowToken() != null) {
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_active_search_cancel || id == R.id.tv_active_search_cancel) {
            etNavSearch.setText("");
        } else if (id == R.id.ll_nav_type) {
            hideKeyBroad();
            imgRateType(ivTriangleType);
            type = 1;
            positionSet = positionSetType;
            showPopWindow();
        } else if (id == R.id.ll_nav_state) {
            hideKeyBroad();
            imgRateState(ivTriangleState);
            type = 2;
            positionSet = positionSetState;
            showPopWindow();
        }
    }
}